package com.ruoyi.flowable.listener;

import com.ruoyi.common.utils.spring.SpringUtils;

import com.ruoyi.flowable.domain.vo.FormDataVo;
import com.ruoyi.flowable.service.IFormDataService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class UserExecutionListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution delegateExecution) {
//        log.info("监听器:{}", JSON.toJSONString(delegateExecution));
        //start end
        if ("end".equals(delegateExecution.getEventName())){
            boolean ended = delegateExecution.isEnded();
//            log.info("是否结束:{}", ended);
            if (ended){
                try {
                    IFormDataService formDataService = SpringUtils.getBean(IFormDataService.class);
                    FormDataVo formData = formDataService.selectFormDataByInstId(delegateExecution.getProcessInstanceId());
                    String tableName = "form_" + formData.getFormId();
                    Map<String, Object> map = new HashMap<>();
                    map.put("data_id", formData.getDataId());
                    map.put("inst_status", "已完成");
                    formDataService.updateMapData(tableName, map);
                }catch (Exception e){
                    log.error(e.getMessage());
                }
            }
        }
    }
}
